// @ts-nocheck
import React, {
  Fragment,
  useCallback,
  useEffect,
  useRef,
  useState,
} from 'react';

import { List, Toast, Avatar, Mask, NavBar } from 'antd-mobile';
import { connect, history } from 'umi';
import { Popup, PopupPosition } from 'react-vant';
import server from '@/utlis/server';
import { Button, message, Upload } from 'antd';
// import ReactSwipe from 'react-swipes'

import './index.less';

import 'lib-flexible';
// import Item from 'antd-mobile/es/components/dropdown/item';
var cameraStream, base64_photo;

export default function index(props) {
  // var cameraVideo = document.getElementById("camera-video")
  // var photo = document.getElementById('show-photo');
  /**
   * 开启摄像头
   */
  let openCamera = () => {
    imgRef.current.src = '';
    cameraVideoref.current.style.display = 'block';
    var letraints = {
      audio: false, //音频轨道
      video: {
        width: '4rem',
        height: '4rem',
      }, //视频轨道
    };
    var mediaPromise = navigator.mediaDevices.getUserMedia(letraints);
    mediaPromise
      .then(function (stream) {
        // console.log('----11');
        /* 使用这个stream stream */
        cameraStream = stream;
        cameraVideoref.current.srcObject = stream;
        cameraVideoref.current.play();
      })
      .catch(function (err) {
        /* 处理error */
        // console.log('----22');
        alert(err);
      });
  };
  /**
   * 拍照
   */
  let getPhoto = () => {
    var canvas = canvasref.current;
    //获取 `canvas`元素，根据`cameraVideo`中的数据进行图片绘制 `ctx.drawImage()`；
    var ctx = canvas.getContext('2d');
    ctx.drawImage(cameraVideoref.current, 0, 0, 300, 150);
    //将 `canvas`绘制的图片信息，展示在 `img`标签中；
    imgRef.current.style.display = 'block';
    setimgsrc(canvas.toDataURL());
    // setTimeout(() => {
    //     imgRef.current.src = canvas.toDataURL();
    // }, 1000);
    cameraVideoref.current.style.display = 'none';
    // 获取base64照片值
    base64_photo = imgRef.current.src;
    // base64转file
    // var file2 = base64ToFile(base64_photo, '文件名');
    // console.log(canvas.toDataURL());
    imguser = canvas.toDataURL();
    setimguser(...imguser);
    edituserimg();
    closeCamera();
    // 等待一会再关闭
    // setTimeout(function () {
    //     closeCamera();
    // }, 200)
  };
  /**
   * 关闭摄像头
   */
  let closeCamera = () => {
    cameraStream.getTracks().forEach(function (track) {
      track.stop();
    });
    cameraVideoref.current.style.display = 'none';
  };

  // imgtobase64
  let imgtobase64 = (e) => {
    var canvas = document.createElement('canvas');
    canvas.width = e.target.width;
    canvas.height = e.target.height;
    var ctx = canvas.getContext('2d');
    ctx.drawImage(e.target, 0, 0, e.target.width, e.target.height);
    var dataURL = canvas.toDataURL('image/png');
    // console.log(dataURL);
    imguser = dataURL;
    setimguser(...imguser);
    edituserimg();
  };
  let [state, setState] = useState<PopupPosition>('');
  let [visible, setvisible] = useState(false);
  let [imgsrc, setimgsrc] = useState('');
  let imgRef = useRef(null);
  let cameraVideoref = useRef(null);
  let canvasref = useRef(null);
  let color = { color: '#1677ff' };
  let [imguser, setimguser] = useState('');
  let [user, setuser] = useState({});
  let onClose = () => {
    setState('');
  };
  // 获取用户信息
  let getuser = async () => {
    let id = props.location.state._id;
    let { data } = await server.get('/userinfo/' + id);
    // console.log(data);
    setuser(data.data);
  };
  useEffect(() => {
    getuser();
  }, []);
  let edituserimg = async () => {
    let { data } = await server.post('/edituserimg', {
      imguser,
      id: props.location.state._id,
    });
    // console.log(data);
    localStorage.setItem('token', data.token);
    setuser(data.user);
    setvisible(false);
  };
  let phone_value = (value) => {
    // console.log(value.splipt(0,4));
    let phone = /^(?:(?:\+|00)86)?1[3-9]\d{9}$/;
    let email = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
    if (phone.test(value)) {
      return value.slice(0, 3) + '****' + value.slice(7);
    } else if (email.test(value)) {
      let values = value.split('@');
      // console.log(values[0].slice(0,3)+'****'+value.slice(7+"@"+"qq.com");

      return values[0].slice(0, 3) + '****' + values[0].slice(7) + '@qq.com';
    }
    // console.log(value.slice(0,3)+'****'+value.slice(7));
  };
  return (
    <div className="myinfo">
      <NavBar
        onBack={() => {
          history.push('/mine');
        }}
      >
        用户信息
      </NavBar>
      <List header="基础信息">
        <List.Item
          onClick={() => {
            setState('bottom');
          }}
          extra={
            <Fragment>
              {user.img ? <Avatar src={user.img} alt="" /> : <Avatar src="" />}
            </Fragment>
          }
        >
          头像
        </List.Item>
        <List.Item
          onClick={() => {
            history.push({
              pathname: '/edituserinfo',
              state: {
                title: '修改昵称',
                _id: user._id,
              },
            });
          }}
          extra={<span style={color}>{user.username}</span>}
        >
          昵称
        </List.Item>
      </List>
      <List header="账号绑定" className="userinfo_usersabd">
        <List.Item
          prefix={
            <Fragment>
              <svg className="icon" aria-hidden="true">
                <use href="#icon-shouji"></use>
              </svg>
            </Fragment>
          }
          onClick={() => {
            history.push({
              pathname: '/edituseremial_phone',
              state: {
                title: '修改手机号',
                _id: user._id,
              },
            });
          }}
          extra={
            <Fragment>
              {user.phone ? (
                <span style={color}>{phone_value(user.phone)}</span>
              ) : (
                <span style={color}>未绑定</span>
              )}
            </Fragment>
          }
        >
          手机
        </List.Item>
      </List>
      <Popup
        visible={state === 'bottom'}
        style={{ height: '30%' }}
        position="bottom"
        description={
          <List mode="card">
            <List.Item
              arrow={false}
              onClick={() => {
                setState('');
                setvisible(true);
                setTimeout(() => {
                  openCamera();
                }, 200);
              }}
            >
              怕一张
            </List.Item>

            <List.Item arrow={false} onClick={() => {}}>
              <Upload
                action="http://localhost:3000/img"
                className="uploadimg"
                showUploadList={false}
                onSuccess={(value) => {
                  console.log(value);
                  imguser = 'http://localhost:3000/' + value.imgurl;
                  setimguser(...imguser);
                  edituserimg();
                }}
              >
                从相册选择
              </Upload>
            </List.Item>

            {/* <Button icon={<UploadOutlined />}>Click to Upload</Button> */}

            <List.Item
              arrow={false}
              onClick={() => {
                setState('');
              }}
            >
              取消
            </List.Item>
          </List>
        }
        onClose={onClose}
      />
      <Mask visible={visible} onMaskClick={() => setvisible(false)}>
        <div className="overlayContent">
          <div className="video_box">
            <video
              id="camera-video"
              ref={cameraVideoref}
              style={{ display: 'none', width: '4rem', height: '4rem' }}
            ></video>
            <img
              src={imgsrc}
              alt=""
              style={{ width: '4rem', height: '4rem', display: 'none' }}
              ref={imgRef}
            />
            <button
              onClick={() => {
                getPhoto();
              }}
            >
              拍照
            </button>
            <br />
            <br />
          </div>
          <canvas
            style={{ width: '4rem', height: '4rem', display: 'none' }}
            ref={canvasref}
          ></canvas>
        </div>
      </Mask>
    </div>
  );
}
